package aleksandar.djuric.offline;

import java.awt.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.LinkedList;

import aleksandar.djuric.common.TimeManagement;
import aleksandar.djuric.entities.Attribute;
import aleksandar.djuric.entities.Player;
import aleksandar.djuric.entities.Team;
import aleksandar.djuric.gui.ColorPane;

public class OfflineDataManager {
	
	private static String myleague;
	
	public static LinkedList<Team> load(ColorPane display){
		File dir = new File(".");
		String[] dirs = dir.list();
		dir = null;
		for (int i = 0; i < dirs.length; i++) {
			if(dirs[i].contains("League") || dirs[i].contains("Division"))
			{
				dir = new File(dirs[i]);
				myleague = dirs[i];
				break;
			}
		}
		LinkedList<Team> teams = new LinkedList<Team>();
		if(dir == null)
			return null;
		Team team = null;
		Player player = null;
		dirs = dir.list();
		File file = null;
		BufferedReader in = null;
		for (int i = 0; i < dirs.length; i++)
		{
			try 
			{
				file = new File(dir + "/" + dirs[i]);
				in = new BufferedReader(
						new InputStreamReader(
						new FileInputStream(file), "UTF-8"));
				String[] array = null;
				String tmp = in.readLine();
				team = new Team(tmp, Integer.parseInt(in.readLine()));
				while((tmp = in.readLine()) != null)
				{
					if(tmp.equals(""))
						continue;
					else if(tmp.contains("Player"))
					{
						array = tmp.split("[ \t]+");
						player = new Player();
						player.setId(Integer.parseInt(
								array[array.length - 1]));
						StringBuilder s = new StringBuilder();
						for (int j = 1; j < array.length - 1; j++) {
							s.append(array[j]);
							if(j != array.length - 2)
								s.append(" ");
						}
						player.setName(s.toString());
						try
						{
							tmp = in.readLine();
							array = tmp.split(",");
							if(array[0].equals("My Character"))
							{
								player.setMyChar(true);
								if(array.length > 1)
									player.setLastOnline(
										TimeManagement.getTM().getDate(
												array[1]));
								if(array.length > 2)
									TimeManagement.getTM().setNextTrainingDate(
											array[2]);
							}
							else
							{
								player.setMyChar(false);
								player.setLastOnline(
										TimeManagement.getTM().getDate(
												array[0]));
							}
							tmp = in.readLine();
							array = tmp.split("birthDate[ \t]+");
							player.setBirthDate(array[1]);
							
							tmp = in.readLine();
							array = tmp.split("userName[ \t]+");
							player.setUserName(array[1]);
							
							tmp = in.readLine();
							array = tmp.split("age[ \t]+");
							player.setAge(Integer.parseInt(array[1]));
							
							tmp = in.readLine();
							array = tmp.split("position[ \t]+");
							player.setPosition(array[1]);
							
							tmp = in.readLine();
							array = tmp.split("aPosition[ \t]+");
							player.setaPosition(array[1]);
							
							tmp = in.readLine();
							array = tmp.split("value[ \t]+");
							player.setValue(Double.parseDouble(array[1]));
							
							tmp = in.readLine();
							array = tmp.split("number[ \t]+");
							player.setNumber(Integer.parseInt(array[1]));
							Attribute[] attribs = 
								new Attribute[Player.attribNames.length];
							for (int j = 0; j < attribs.length; j++) 
							{
								tmp = in.readLine();
								if(tmp.startsWith("-"))
								{
									j -= 1;
									continue;
								}
								String tmp1 = tmp.substring(
										tmp.indexOf("(") + 1,
										tmp.indexOf(")"));
								try
								{
									attribs[j] = new Attribute(
											Double.parseDouble(tmp1));
								}
								catch(NumberFormatException e)
								{
									attribs[j] = new Attribute(
											tmp.substring(
													tmp.lastIndexOf("  ") + 2,
													tmp.lastIndexOf(" ")));
								}
							}
							player.setAttribs(attribs);
							
							in.readLine();
							tmp = in.readLine();
							String[] sAbility = null;
							if(tmp.equals("special abilities"))
							{
								while(!(tmp = in.readLine()).equals(""))
								{
									sAbility = tmp.split("_");
									player.addSpecialAbility(sAbility[0],
											Integer.parseInt(sAbility[1]));
								}
							}
						}
						catch(ArrayIndexOutOfBoundsException e)
						{
							display.append(Color.RED, 
									" Invalid player data. - " 
									+ player.getName() 
									+ "\n"
									+ team.getName()
									+ "\n");
						}
						catch(NumberFormatException e)
						{
							display.append(Color.RED, 
									" Invalid player data. - " 
									+ player.getName() 
									+ "\n"
									+ team.getName()
									+ "\n");
						}
						catch(StringIndexOutOfBoundsException e)
						{
							display.append(Color.RED, 
									" Invalid player data. - " 
									+ player.getName() 
									+ "\n"
									+ team.getName()
									+ "\n");
						}
						
						team.addPlayer(player);
					}				
				}
				in.close();
				teams.add(team);
			}
			catch (FileNotFoundException e) {
				e.printStackTrace();
			} 
			catch (IOException e) {
				e.printStackTrace();
			}
			catch (NumberFormatException e)
			{
				e.printStackTrace();
			}
		}
		return teams;
	}
	
	public static String getMyleague() {
		return myleague;
	}

	public static void setMyleague(String myleague) {
		OfflineDataManager.myleague = myleague;
	}

	public static void write(LinkedList<Team> teams)
	{
		File dir = new File(getMyleague());
		if(!dir.exists())
		{
			dir.mkdir();
		}
		else
		{
			File[] filenames = dir.listFiles();
			for (int i = 0; i < filenames.length; i++) {
				filenames[i].delete();
			}
		}
		if(teams != null)
			for (int i = 0; i < teams.size(); i++) {
				write(teams.get(i));
			}
	}
	
	public static void write(Team team)
	{
		PrintWriter out;
		try {
			out = new PrintWriter(new File(getMyleague()
					+ "/" + team.getName() + ".txt"), "UTF-8");
			out.println(team.getName()); 
			out.println(team.getId());
			out.println();
			if(team.getNPlayers() != 0)
			{
				for (int j = 0; j < team.getNPlayers(); j++) {
					Player curPlayer = team.getPlayer(j);
					out.println(curPlayer.toStringFull());
					out.println();
					out.println("--------------------------" +
								"------------------------------");
					out.println();
				}
			}
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	public static void write(String stats)
	{
		PrintWriter out;
		try {
			out = new PrintWriter(new File("stats.txt"), "UTF-8");
			out.println(stats); 
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		LinkedList<Team> teams = OfflineDataManager.load(new ColorPane());
		System.out.println(teams);
		for (int i = 0; i < teams.size(); i++) {
			System.out.println(Arrays.toString(teams.get(i).getPlayerNames()));
		}
	}
	
	

}
